
//
// 120129 - AH - (Midtun) Created.
//

package org.soekrat.gui.swing.tools;

import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;

import org.soekrat.gui.swing.TestFrame;

/**
 * <p>
 *   {@link JComboBox} that has a fixed size and the selected object's textual
 *   presentation is showed as tool tip text.  
 * </p>
 * @author Arne Halvorsen (AH)
 */
@SuppressWarnings("serial")
public final class ToolTipComboBox extends JComboBox 
{
  /**
   * <p>
   *   Creates of default fixed width.
   * </p>
   */
  public ToolTipComboBox(){ this(100); }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param maxWidth Maximum width. 
   */
  public ToolTipComboBox(int maxWidth)
  {
    if (maxWidth<1)
    {
      throw new IllegalArgumentException("maxWidth<1 : "+maxWidth);  
    }
    
    Dimension d=getPreferredSize();
    d.width=maxWidth;
    setMaximumSize(d);
    setPreferredSize(d);
    setMinimumSize(d);
    
    addItemListener
    (
      new ItemListener() 
      {
        public void itemStateChanged(ItemEvent e)
        {
          setsToolTipTextFromSelected();
        }
      }
    );

    setsToolTipTextFromSelected();
  }
  
  private void setsToolTipTextFromSelected()
  {
    Object s=getSelectedItem();
    String ftxt=(s==null) ? "" : s.toString();
    setToolTipText(ftxt);
  }
  
  public static void main(String[] args) 
  {
    TestFrame.show(new ToolTipComboBox());  
  }
  
}
